package com.pay.game.central.web.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.fasterxml.uuid.Generators;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pay.game.central.common.Result;
import com.pay.game.central.common.ResultGenerator;
import com.pay.game.central.security.annotaion.PassToken;
import com.pay.game.central.security.annotaion.UserLoginToken;
import com.pay.game.central.system.bean.User;
import com.pay.game.central.system.mapper.UserMapper;
import com.pay.game.central.utils.DateTimeUtil;
import com.pay.game.central.utils.RequestUtils;
import com.pay.game.central.utils.bean.MyHeader;
import com.pay.game.central.web.bean.PtScore;
import com.pay.game.central.web.bean.Store;
import com.pay.game.central.web.service.GoodsService;
import com.pay.game.central.web.service.PtScoreService;
import com.pay.game.central.web.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("store")
@Controller
public class StoreController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private PtScoreService scoreService;

    @Autowired
    private UserMapper userMapper;

//    /**
//     * 添加一个商店
//     * @return 是否添加成功
//     */
//    @PostMapping
//    @ResponseBody
//    Result<Boolean> addStore(String store_id,String store_name){
//        storeService.addStore(store_id, store_name, "");
//        return ResultGenerator.genSuccessResult(true);
//    }

    @UserLoginToken
    @PostMapping("/{id}/loop")
    @ResponseBody
    Result<String> setLoop(@PathVariable String id, boolean loop, String userId){
        if (loop){
            storeService.startLoop(id);
        }else {
            storeService.stopLoop(id, userId);
        }
        return ResultGenerator.genSuccessResult("设置成功");
    }

    @UserLoginToken
    @PostMapping("/score")
    @ResponseBody
    Result<String> setScore(@RequestBody String body,@RequestHeader Map<String, String> headers){
        JSONObject jsonObject = JSON.parseObject(body);
        int score = jsonObject.getInteger("score");
        JSONArray jsonArray = jsonObject.getJSONArray("storeIds");
        List<String> storeIds =jsonArray.stream().map(Object::toString).collect(Collectors.toList());
        MyHeader myHeader = RequestUtils.parseHeader(headers);
        storeIds.forEach(id -> storeService.setScore(id, myHeader.getUserId(), score));
        return ResultGenerator.genSuccessResult("操作成功");
    }

    @UserLoginToken
    @PostMapping("/{id}/score/add")
    @ResponseBody
    Result<String> addScore(@PathVariable String id, @RequestBody String body,@RequestHeader Map<String, String> headers){
        JSONObject jsonObject = JSON.parseObject(body);
        int score = jsonObject.getInteger("score");
        storeService.addScore(id, score);
        String token = headers.get("x-token");
        // 获取操作用户
        String userId = JWT.decode(token).getAudience().get(0);
        PtScore ptScore = new PtScore();
        ptScore.setId(Generators.timeBasedGenerator().generate().toString());
        ptScore.setOpt_time((int) (System.currentTimeMillis()/1000));
        ptScore.setStore_id(id);
        ptScore.setValue(score);
        ptScore.setUser_id(userId);
        //保存记录
        scoreService.insertItem(ptScore);
        return ResultGenerator.genSuccessResult("操作成功");
    }

    /**
     * 导入Excel
     * @param body
     * @return
     */
    @PostMapping("/import")
    @ResponseBody
    @UserLoginToken
    Result<String> importStore(@RequestBody String body){
        JSONArray array = JSON.parseArray(body);
        List<Store> pddStores = array.stream().map(obj -> {
            JSONObject object = (JSONObject) obj;
            Store store = new Store();
            store.setId(object.getString("店铺ID"));
            store.setName(object.getString("店铺名称"));
            store.setCreate_time(System.currentTimeMillis());
            return store;
        }).collect(Collectors.toList());
        storeService.queryAll().forEach(pddStore -> {
            Store temp = null;
            for (Store s1: pddStores) {
                if(s1.getId().equals(pddStore.getId())){
                    temp = s1;
                    break;
                }
            }
            pddStores.remove(temp);
        });
        List<Store> stores = pddStores.stream().distinct().collect(Collectors.toList());
        if (pddStores.size() > 0) storeService.addStores(stores);
        return ResultGenerator.genSuccessResult("导入成功");
    }

    /**
     * 删除店铺
     * @param id
     * @return
     */
    @PostMapping("/deleteOne")
    @ResponseBody
    Result<Boolean> deleteStoreById(String id){
        storeService.deleteById(id);
        return ResultGenerator.genSuccessResult(true);
    }

    /**
     *
     * @return 所有店铺信息
     */
    @GetMapping("/list")
    @ResponseBody
    @UserLoginToken
    Result<PageInfo<Map<String, Object>>> list(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "20") int limit,
                                 String id, String username, String storeName){
        PageHelper.startPage(page,limit);
        return ResultGenerator.genSuccessResult(new PageInfo<>(storeService.list(id, storeName, username)));
    }

    @PostMapping("/userId")
    @UserLoginToken
    @ResponseBody
    Result<String> setStoreUserId(@RequestBody String body) {
        JSONObject jsonObject = JSON.parseObject(body);
        JSONArray jsonArray = jsonObject.getJSONArray("storeIds");
        List<String> storeIds =jsonArray.stream().map(Object::toString).collect(Collectors.toList());
        String userId = jsonObject.getString("userId");
        storeService.setStoresUserId(storeIds, userId);
        return ResultGenerator.genSuccessResult("设置成功");
    }

    @PostMapping("/edit")
    @UserLoginToken
    @ResponseBody
    Result<String> edit(@RequestHeader Map<String, String> headers,@RequestBody String body ){
        MyHeader myHeader = RequestUtils.parseHeader(headers);
        JSONObject jsonObject = JSON.parseObject(body);
        String storeId =  jsonObject.getString("storeId");
        List<String> storeIds = new ArrayList<>();
        storeIds.add(storeId);
        String userId = jsonObject.getString("userId");
        int score = jsonObject.getInteger("score") * 100;
        boolean loop = "true".equals(jsonObject.getString("loop"));
        boolean old_loop = "true".equals(jsonObject.getString("old_loop"));
        storeService.setStoresUserId(storeIds, userId);
        storeService.setScore(storeId, myHeader.getUserId(), score);
        if(loop != old_loop) {
            if (loop){
                storeService.startLoop(storeId);
            }else {
                storeService.stopLoop(storeId, myHeader.getUserId());
            }
        }
        return ResultGenerator.genSuccessResult("success");
    }

    /**
     * 移除店铺的归属用户
     */
    @PostMapping("/removeUserId")
    @UserLoginToken
    @ResponseBody
    Result<String> removeUserId(@RequestBody String body){
        JSONObject jsonObject = JSON.parseObject(body);
        String storeId = jsonObject.getString("storeId");
        storeService.setStoreUserId(storeId,"");
        return ResultGenerator.genSuccessResult("设置成功");
    }

    @GetMapping("/noUserId")
    @UserLoginToken
    @ResponseBody
    Result<List<Store>> noUserId(String storeId){
        return ResultGenerator.genSuccessResult(storeService.queryNoUserId(storeId));
    }


    /**
     * 获取没有爬取的商店
     */
    @GetMapping("/not-spider")
    @ResponseBody
    Result<List<Store>> notSpider(){
        return ResultGenerator.genSuccessResult(storeService.getNotSpider());
    }

    @PostMapping("/list")
    @PassToken
    @ResponseBody
    Result<String> addStores(@RequestBody String body){
        String timeString = DateTimeUtil.getFormatCurrentDate("yyMMddHHmm");
        JSONObject jsonObject = JSON.parseObject(body);
        JSONArray list = jsonObject.getJSONArray("stores");
        String username = jsonObject.getString("username");
        if (StringUtils.isEmpty(username)) return  ResultGenerator.genFailResult("用户名不能为空");
        User user = userMapper.findUserByUserName(username);
        if (null == user) return  ResultGenerator.genFailResult("无效用户，请确定用户已注册");
        list.forEach(store -> {
            JSONObject object = (JSONObject) store;
            storeService.updateOrAddStore(
                    object.getString("id"),
                    object.getString("name"),
                    object.getString("thumb_url"),
                    user.getId(),
                    timeString +object.getString("index")
            );
        });
        return ResultGenerator.genSuccessResult("成功");
    }

}
